import { getLocalStorage } from '@/utils/common.js'
import Service from '@/utils/service.js'
import { useRoutesStore } from './routes.js'
import { useTagsBarStore } from './tagsBar.js'

const isDev = import.meta.env.DEV
const userInfo = getLocalStorage('userInfo')

export const useAppStore = defineStore({
  id: 'app',
  state: () => ({
    token: userInfo?.token,
    realName: userInfo?.realName,
  }),
  actions: {
    async login({ username, password }) {
      try {
        const { code, data } = await Service.postAction('/login', { username, password })
        if (code === 200) {
          const { token, realName } = data
          this.token = token
          this.realName = realName
          localStorage.setItem('userInfo', JSON.stringify({ token, realName }))
          return true
        }
      } catch (e) {
        return false
      }
    },
    logout() {
      const routesStore = useRoutesStore()
      const tagBarStore = useTagsBarStore()
      this.token = ''
      localStorage.removeItem('userInfo')
      // isDev &&
      //   setTimeout(() => {
      //     routesStore.resetRoutes()
      //     tagBarStore.resetTagBar()
      //   }, 500)
    },
  },
})
